import React, {Component} from 'react';
import Button from 'antd/lib/button';
import {Table, Modal, Input, Icon} from 'antd';
import QRCode from "qrcode.react";
import {postDataV2 as postData} from '../../../utils/request';
import {
  createParams,
  updateParams,
  getParamsList,
  deleteParams,
} from '../../../utils/queryData';

import './index.scss';

export default class DefaultParams extends Component {
  state = {
    page: 1,
    pageSize: 10,
    query: {},
    paramsList: [],
    modalVisible: false,
    formObj: {
      code: '',
      description: '',
      params: '{}',
    },
  };
  addParams = () => {
    this.setState ({
      modalVisible: true,
      formObj: {
        code: '',
        description: '',
        params: '{}',
      },
    });
  };
  onChangeText = (key, e) => {
    this.setState ({
      formObj: {
        ...this.state.formObj,
        [key]: e.target.value,
      },
    });
  };
  handleOk = () => {
    let {_id, code, description, params} = this.state.formObj;
    let query = _id
      ? updateParams (_id, {code, description, params})
      : createParams ({code, description, params});
    if (query) {
      postData ('', {query}).then (res => {
        if (res.errors) {
          Modal.error ({
            title: '啊席八',
            content: res.errors[0].message,
          });
        } else {
          this.getParamsList ();
        }
      });
      this.setState ({
        modalVisible: false,
        formObj: {
          code: '',
          description: '',
        },
      });
    }
  };
  deleteParamsFnc = props => {
    Modal.confirm ({
      title: '提示',
      content: '确定删除该cmd吗',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        postData ('', {query: deleteParams (props._id)}).then (res => {
          this.getParamsList ();
        });
      },
      onCancel () {
        console.log ('Cancel');
      },
    });
  };
  editCmd = ({_id, code, description, params}) => {
    this.setState ({
      modalVisible: true,
      formObj: {
        _id,
        code,
        description,
        params,
      },
    });
  };
  handleCancel = () => {
    this.setState ({modalVisible: false});
  };
  getParamsList = () => {
    let {page, pageSize, params} = this.state;
    postData ('', {
      query: getParamsList ({page, pageSize, params}),
    }).then (res => {
      let list = res.data.defaultParams.list;
      list = list.map (item => {
        return {
          ...item,
          params: JSON.stringify (item.params, null, 4),
        };
      });
      this.setState ({paramsList: list});
    });
  };
  showSuccess = (title, content) => {
    Modal.success({
        title: title,
        content: content,
        width: 560
    });
  };
  preview = props => {
    let options = {
      cmd: props.code,
      data: JSON.parse (props.params),
      description: props.description
    };
    let query = encodeURIComponent(JSON.stringify (options));
    let title = '链接生成成功！',
      url = `http://kflryw.fxwork.kugou.com/callupV2/mobile/?query=${query}`,
      msg = (
        <div>
          <p className="dialog-message">
            请访问：<a href={url} target="_blank" rel="noopener noreferrer">
              {url}
            </a>
          </p>
          <QRCode value={url} />
        </div>
      );
    this.showSuccess (title, msg);
  };
  componentDidMount () {
    this.getParamsList ();
  }
  render () {
    const {paramsList, modalVisible, formObj} = this.state;
    const columns = [
      {
        title: 'Cmd',
        dataIndex: 'code',
      },
      {
        title: '作用',
        dataIndex: 'description',
      },
      {
        title: '参数',
        render: props => (
          <Input
            type="textarea"
            value={props.params}
            disabled
            autosize={{minRows: 2}}
          />
        ),
      },
      {
        title: '操作',
        dataIndex: '',
        render: props => (
          <div>
            <Button
              type="primary"
              onClick={() => {
                this.editCmd (props);
              }}
            >
              编辑
            </Button>&nbsp;&nbsp;<Button
              type="danger"
              onClick={() => {
                this.deleteParamsFnc (props);
              }}
            >
              删除
            </Button>&nbsp;&nbsp;<Button
              onClick={() => {
                this.preview (props);
              }}
            >
              预览
            </Button>
          </div>
        ),
      },
    ];
    return (
      <div className="default-params">
        <Button type="primary" onClick={this.addParams}>添加参数</Button>
        <h3>参数列表</h3>
        <div>
          <Table
            width="600px"
            columns={columns}
            dataSource={paramsList}
            bordered
          />
        </div>
        <Modal
          width="400px"
          title="添加/编辑cmd参数"
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          cancelText="取消"
          okText="确认"
        >
          <div className="modal-inner">
            <Input
              placeholder="输入cmd"
              prefix={
                <Icon type="android" style={{color: 'rgba(0,0,0,.25)'}} />
              }
              suffix={
                !!formObj.code
                  ? <Icon type="close-circle" onClick={this.cleanCmdInput} />
                  : null
              }
              value={formObj.code}
              onChange={e => {
                this.onChangeText ('code', e);
              }}
              ref={node => (this.userNameInput = node)}
            />
            <Input.TextArea
              onChange={e => {
                this.onChangeText ('description', e);
              }}
              placeholder="输入参数作用"
              value={formObj.description}
              autosize={{minRows: 2, maxRows: 6}}
            />
            <Input.TextArea
              onChange={e => {
                this.onChangeText ('params', e);
              }}
              placeholder="输入参数"
              value={formObj.params}
              autosize={{minRows: 2, maxRows: 6}}
            />
          </div>
        </Modal>
      </div>
    );
  }
}
